package com.jgy.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jgy.annotation.SetLogValue;
import com.jgy.entity.Role;
import com.jgy.entity.RolePermission;
import com.jgy.entity.SpaceUser;
import com.jgy.entity.UserRole;
import com.jgy.mapper.PermissionMapper;
import com.jgy.mapper.RoleMapper;
import com.jgy.utils.CommonConstants;
import com.jgy.utils.R;
import com.jgy.utils.SecurityUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 姜光远
 * @date 2022/10/29 16:41
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Resource
    RoleMapper roleMapper;
    @Resource
    PermissionMapper permissionMapper;
    @Resource
    private HttpServletRequest request;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;


    //获取权限表数据
    @SetLogValue(modular = "权限模块",type = CommonConstants.SELECT, describe = "查询权限")
    @GetMapping("/selectRoleList")
    public R<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                         @RequestParam(defaultValue = "10") Integer pageSize,
                         @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<Role> wrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Role::getName, search);
        }
        Page<Role> RolePage = roleMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        List<Role> records = RolePage.getRecords();
        // 给角色设置绑定的权限id数组
        for (Role record : records) {
            Integer roleId = record.getId();
            List<Integer> permissions = permissionMapper.getRolePermissionByRoleId(roleId).stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
            record.setPermissions(permissions);
        }
        return R.ok(RolePage);
    }

    // 改变权限接口
    @SetLogValue(modular = "权限模块",type = CommonConstants.UPDATE, describe = "更新权限")
    @PutMapping("/changePermission")
    public R<?> changePermission(@RequestBody Role role) {
        // 先根据角色id删除所有的角色跟权限的绑定关系
        permissionMapper.deletePermissionsByRoleId(role.getId());
        // 再新增 新的绑定关系
        for (Integer permissionId : role.getPermissions()) {
            permissionMapper.insertRoleAndPermission(role.getId(), permissionId);
        }

        // 判断当前登录的用户角色是否包含了当前操作行的角色id，如果包含，则返回true，需要重新登录。
        SpaceUser user1 = SecurityUtil.getUser();

        List<UserRole> userRoles = roleMapper.getUserRoleByUserId(Integer.parseInt(user1.getId()));
        if (userRoles.stream().anyMatch(userRole -> userRole.getRoleId().equals(role.getId()))) {
            return R.ok(true);
        }
//        如果不包含，则返回false，不需要重新登录。
        return R.ok(false);
    }

    //所有role列表
    @SetLogValue(modular = "权限模块",type = CommonConstants.SELECT, describe = "查询所有权限")
    @GetMapping("/all")
    public R<?> all() {
        return R.ok(roleMapper.selectList(null));
    }

    //新政role列表
    @SetLogValue(modular = "权限模块",type = CommonConstants.ADD, describe = "新增权限")
    @PostMapping("/saveRole")
    public R<?> save(@RequestBody Role role) {
        roleMapper.insert(role);
        return R.ok();
    }

    //修改role列表
    @SetLogValue(modular = "权限模块",type = CommonConstants.UPDATE, describe = "修改权限")
    @PutMapping("/updateRole")
    public R<?> update(@RequestBody Role role) {
        roleMapper.updateById(role);
        return R.ok();
    }

    //删除role列表信息
    @SetLogValue(modular = "权限模块",type = CommonConstants.DELETE, describe = "删除权限")
    @DeleteMapping("/deleteRole")
    public R<?> deleteRole(@RequestParam(value = "id") Long id) {
        roleMapper.deleteById(id);
        return R.ok();
    }
}
